#!/usr/bin/env python

# -*- coding: utf-8 -*-

import sys

from win32 import win32api
from win32 import win32gui
from win32.lib import win32con

from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *


#pip install keyboard mouse
import keyboard
import pyperclip

import sys
import logging
sys.path.append('core')
sys.path.append('lib/sys')
sys.path.append('lib/user')

import os 
import fnmatch
import xml
import random
import re
import bzd
import bot
import dbmanage
import traceback

from logging import handlers

class Logger(object):
    level_relations = {
        'debug':logging.DEBUG,
        'info':logging.INFO,
        'warning':logging.WARNING,
        'error':logging.ERROR,
        'crit':logging.CRITICAL
    }#日志级别关系映射

    def __init__(self,filename,level='info',when='D',backCount=3,fmt='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'):
        self.logger = logging.getLogger(filename)
        format_str = logging.Formatter(fmt)#设置日志格式
        self.logger.setLevel(self.level_relations.get(level))#设置日志级别
        sh = logging.StreamHandler()#往屏幕上输出
        sh.setFormatter(format_str) #设置屏幕上显示的格式
        th = handlers.TimedRotatingFileHandler(filename=filename,when=when,backupCount=backCount,encoding='utf-8')#往文件里写入#指定间隔时间自动生成文件的处理器
        #实例化TimedRotatingFileHandler
        #interval是时间间隔，backupCount是备份文件的个数，如果超过这个个数，就会自动删除，when是间隔的时间单位，单位有以下几种：
        # S 秒
        # M 分
        # H 小时、
        # D 天、
        # W 每星期（interval==0时代表星期一）
        # midnight 每天凌晨
        th.setFormatter(format_str)#设置文件里写入的格式
        self.logger.addHandler(sh) #把对象加到logger里
        self.logger.addHandler(th)


        
log = Logger('log/error.log',level='debug')

dbmanage.reset()

def process(userinput):
    answer = bot.chatToBot(userinput,True)
    if(answer==""):
        answer = bzd.getAnswer(userinput)
    print('uibot:'+answer)
    
def run(userinput):
    try:
       process(userinput) 
    except Exception as ex:
        #问题语句写入log
        log.logger.error(userinput)
        log.logger.error(ex)

pyperclip.copy("hello world")


class Window(QWidget):
    sigWindow = pyqtSignal()
    def __init__(self, *args, **kwargs):
        super(Window, self).__init__(*args, **kwargs)
        #获取显示器分辨率大小
        self.desktop = QApplication.desktop()
        self.screenRect = self.desktop.screenGeometry()
        self.height = self.screenRect.height()
        self.width = self.screenRect.width()
        self.rate = self.height*1.0/1080
        self.sigWindow.connect(self.onShowWindow, type=Qt.QueuedConnection)
        self.setObjectName("root")
        #QFontDatabase.addApplicationFont("ResourceHanRoundedCN-ExtraLight.ttf")#Resource Han Rounded CN ExtraLight
        self.setFixedSize(int(600*self.rate),int(68*self.rate))
        #保持始终在顶部开始显示
        self.setWindowFlag(Qt.WindowStaysOnTopHint)
        self.setWindowFlag(Qt.FramelessWindowHint)
        self.setAttribute(Qt.WA_TranslucentBackground)
        layout = QVBoxLayout(self)
        self.bgframe = QFrame(self)
        self.bgframe.setObjectName("bgframe")
        layout.addWidget(self.bgframe)
        frlayout = QVBoxLayout(self.bgframe)
        self.textinput = QLineEdit(self)
        self.textinput.setObjectName("textinput")
        frlayout.addWidget(self.textinput)
        #frlayout.addWidget(QPushButton(
            #"退出整个程序", self, clicked=self.onQuit))
        pl = self.textinput.palette()
        pl.setBrush(QPalette.Base,QBrush(QColor(255,0,0,0)))
        self.textinput.setPalette(pl)
        self.setStyleSheet("QWidget#root{padding:0px;}"
        "QFrame#bgframe{background:#CF000000;border-radius:%ipx;border:%ipx solid #AFAFAF;}"
        "QLineEdit#textinput{border:0px;background:transparent;font-family: \"微软雅黑\";font-weight:bold;font-size:%ipx;color:#ffffff;}"%(4*self.rate,self.rate,14*self.rate))
        self.textinput.focusOutEvent = self.focusOutEvent
        # 拦截系统的快捷键,suppress=True表示拦截,不传递到其它程序
        keyboard.add_hotkey('F23', self.onShow, suppress=True,trigger_on_release=True)  # 显示界面
        keyboard.add_hotkey('F24', self.onHide, suppress=True)  # 隐藏界面
        keyboard.add_hotkey('ctrl+F12', self.onQuit, suppress=True)  # 退出程序
        keyboard.add_hotkey('enter', self.onEnter, suppress=False)  # 退出程序

        # 这个函数类似while True，由于这里有界面GUI的loop事件，可以达到类似的效果
#         keyboard.wait()#Block forever, like `while True`.==

    def paste(self):
        ##CTRL-A
            '''win32api.keybd_event(win32con.VK_LCONTROL,0x1d, 0, 0)
            win32api.keybd_event(win32api.VkKeyScan('A'),0x1e, 0, 0)
            win32api.keybd_event(win32api.VkKeyScan('A'),0x9e, win32con.KEYEVENTF_KEYUP, 0)
            win32api.keybd_event(win32con.VK_LCONTROL,0x9d, win32con.KEYEVENTF_KEYUP, 0)
            time.sleep(.1)'''
        ##CTRL-V
            win32api.keybd_event(win32con.VK_LCONTROL,0x1d, 0, 0)
            win32api.keybd_event(win32api.VkKeyScan('V'),0xaf, 0, 0)
            win32api.keybd_event(win32api.VkKeyScan('V'),0x2f, win32con.KEYEVENTF_KEYUP, 0)
            win32api.keybd_event(win32con.VK_LCONTROL,0x9d, win32con.KEYEVENTF_KEYUP, 0)
            #print ("CTRL-V")
            #time.sleep(.1)

    def onShow(self):
        '''
        print("onShow")
        hwnd  = win32gui.GetForegroundWindow()
        print(hwnd)

        point = win32api.GetCursorPos()
        subHandle =win32gui.ChildWindowFromPoint(hwnd,point)
        print(subHandle)
        #subHandle = win32gui.WindowFromPoint(point)
        bufSize = win32api.SendMessage(subHandle, win32con.WM_GETTEXTLENGTH, 0, 0) +1
        # 利用api生成Buffer
        strBuf = win32gui.PyMakeBuffer(bufSize)
        length = win32gui.SendMessage(subHandle, win32con.WM_GETTEXT, bufSize, strBuf)
        address, length = win32gui.PyGetBufferAddressAndLen(strBuf) 
        text = win32gui.PyGetString(address, length) 
        print(text)'''
        """显示"""

        #self.logView.append('按下alt+s')
        self.textinput.clear()
        self.textinput.setFocus()
        self.activateWindow()
        self.setWindowState(self.windowState() & ~Qt.WindowMinimized | Qt.WindowActive)
        self.showNormal()
        self.show()
        #self.dialogShow.emit()
        #keyboard.write("test")

    def focusOutEvent(self, e):
        self.hide()

    def onShowWindow(self):
        #run
        process(self.textinput.text())
        #self.label = QLabel('111')
        #self.label.show()
        #QMessageBox.information(self, '对话框', '按下alt+s键')

    def onEnter(self):
        if self.textinput.hasFocus():
            self.hide()
            if(self.textinput.text()=='重新加载'):
                dbmanage.reload()
            self.sigWindow.emit()
        
    def onHide(self):
        self.hide()

    def onQuit(self):
        """退出函数"""
        keyboard.unhook_all_hotkeys()  # 取消所有热键
        QApplication.instance().quit()

    def closeEvent(self, event):
        # 忽略关闭窗口,直接隐藏
        self.hide()
        return event.ignore()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    app.setQuitOnLastWindowClosed(False)
    w = Window()
    w.show()
    sys.exit(app.exec_())
    print("finish")
